from time import time

# 作用域之间的转换
# 将局部变量变成全局变量
a = 1


def foo():
    global a
    a = 2
    print(a)


foo()
print(a)


# 将局部变量变成自由变量


def make_averager():
    total = 0
    count = 0

    def averager(value):
        nonlocal total, count
        total += value
        count += 1
        return total / count

    return averager


my_avg = make_averager()
print(my_avg(1))
print(my_avg(2))


# 输出函数执行时间装饰器
def clock_it_deco(fun):
    def wrapper(*args, **kwargs):
        start_time = time()
        result = fun(*args, **kwargs)
        end_time = time()
        print(f"{fun.__name__} 执行时间：{format(end_time - start_time, '.2f')} 秒")
        return result

    return wrapper


@clock_it_deco
def foo(a, b):
    count = 1
    while True:
        if count > a ** b:
            break
        count += 1


foo(10, 5)

# fibo缓存
a = {}


def cache_deco(func):
    global a

    def wrap(n):
        if n not in a:
            a[n] = func(n)
        return a[n]

    return wrap


@cache_deco
def fib(n):
    if n < 2:
        return n
    else:
        return fib(n - 2) + fib(n - 1)


print(fib(10))
print(a)
